package com.example.Cairodio;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

import com.facebook.android.AsyncFacebookRunner;
import com.facebook.android.DialogError;
import com.facebook.android.Facebook;
import com.facebook.android.Facebook.DialogListener;
import com.facebook.android.FacebookError;
import com.facebook.android.Util;

/**
 * This class is responsible for initating a connection with Facebook, then using it 
 * to upload a photo to the application photo album.
 * @author AnwaRowers
 *
 */
public class FacebookConnection extends Activity {
    Facebook facebook;
    SharedPreferences mPrefs;
    String permissions[];
    Bitmap bitmap; 
    String user_id = ""; 
    
    
    /**
     * restore the previous session on Facebook if valid, or else authenticate.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);       
        bitmap = (Bitmap) getIntent().getParcelableExtra("BitmapImage");
        mPrefs = getPreferences(MODE_PRIVATE);
        facebook = new Facebook(getString(R.string.app_id));
        permissions = getResources().getStringArray(R.array.permissions);
        String access_token = mPrefs.getString("access_token", null);
        long expires = mPrefs.getLong("access_expires", 0);
        
        if(access_token != null) {
            facebook.setAccessToken(access_token);
            Toast.makeText(this, getString(R.string.logged_in), 1).show();
        }
        if(expires != 0) {
            facebook.setAccessExpires(expires);
        }
        
        if(!facebook.isSessionValid()) {
        	
        	Toast.makeText(this, getString(R.string.authenticating), 1).show();
            facebook.authorize(this, permissions, new AuthDialogListener(this));
        } else{
        	this.uploadPhoto(bitmap);
        }
        
     
        }
        
        
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        facebook.authorizeCallback(requestCode, resultCode, data);
    }

    public void uploadPhoto(Bitmap bitmap) {
    	if(!facebook.isSessionValid()) {
    		Toast.makeText(this, getString(R.string.session_invalid), 1);
    	}
    	if(bitmap == null) {
    		 Toast.makeText(this, getString(R.string.null_bitmap), 1).show();
    	 }else {
    		 UploadPhoto uploadPhoto =  new UploadPhoto(facebook);
    		 uploadPhoto.postImageonWall(bitmap);
    		 finalizeAndReturn();
    	 }
    }
    
    private void finalizeAndReturn() {
        Intent intent = new Intent();
        setResult(RESULT_OK, intent);
        finish();
    }
}

class AuthDialogListener implements DialogListener {
	FacebookConnection facebookTutorial; 
	public AuthDialogListener(FacebookConnection fbTut) {
		this.facebookTutorial = fbTut; 
	}
	public void onComplete(Bundle values) {
        SharedPreferences.Editor editor = facebookTutorial.mPrefs.edit();
        editor.putString("access_token", facebookTutorial.facebook.getAccessToken());
        editor.putLong("access_expires", facebookTutorial.facebook.getAccessExpires());
        editor.commit();
        AsyncFacebookRunner fbRunner = new AsyncFacebookRunner(facebookTutorial.facebook);
        this.facebookTutorial.uploadPhoto(this.facebookTutorial.bitmap);
    }
	
	 public void onFacebookError(FacebookError error) {
     	Toast.makeText(this.facebookTutorial, this.facebookTutorial.getString(R.string.error), 1).show();
     }
     	
     
     public void onError(DialogError e) {
    	 Toast.makeText(this.facebookTutorial, this.facebookTutorial.getString(R.string.error), 1).show();
     }

     
     public void onCancel() {}
}


class IDRequestListener extends BaseRequestListener {
	 
	
	public void onComplete(String response, Object state) {
		try {
			Log.d("IDRequestListener", "Response: " + response.toString());
			JSONObject json = Util.parseJson(response);
			final String id = json.getString("id");
			Log.d("IDRequestListener", "userid is "+ id);
		} catch (JSONException e) {
			Log.w("IDRequestListener", "JSON Error in response");
		} catch (FacebookError e) {
			Log.w("IDRequestListener", "Facebook Error: " + e.getMessage());
		}
	}

}